import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wan_android/pages/item_artical.dart';
import 'package:wan_android/pages/page_web.dart';

///首页界面
class PageHome extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState

    return PageHomeState();
  }
}

class PageHomeState extends State<PageHome> {
  /// pageView 控制器
  PageController pageController = new PageController();

  ///banner 列表
  final List<BannerEntity> bannerList = [];

  int _currentPage = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getBannerData();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    print("home 创建条目:");

    return Column(
      children: <Widget>[
        Container(
          height: 180.0,
//          decoration: BoxDecoration(color: Colors.red),
          child: PageView.builder(
            itemBuilder: (BuildContext context, int dex) {
              return _getBannerUi(bannerList[dex]);
            },
            itemCount: bannerList.length,
            controller: pageController,
            onPageChanged: _listenPageChange,
          ),
        ),
        Expanded(
          child: Container(
            padding: EdgeInsets.only(top: 5.0),
            child: ItemWidget(
              ////'http://www.wanandroid.com/article/list/$pageIndex/json'
              firApi: 'http://www.wanandroid.com/article/list/',
              secApi: '/json',
              isFavorite: false,
              isSearch: false,
            ),
          ),
        ),
      ],
    );
  }

  //获取Banner数据
  _getBannerData() async {
    Dio dio = new Dio();
    await dio.get('http://www.wanandroid.com/banner/json').then((value) {
      /// 获取到返回值
      print('开始请求头部文件');
      for (var value1 in value.data['data']) {
        BannerEntity entity = BannerEntity.fromJson(value1);
        bannerList.add(entity);
      }
      print('请求成功');
      setState(() {});
    }).catchError((error) {
      print('请求出现异常');
      print(error);
    }).whenComplete(() {
      print('已经完成');
      _keepBannerRunning();
    });
  }

  ///实现定时轮播
  _keepBannerRunning() {
    /// 定时执行专用
    Timer.periodic(Duration(seconds: 3), (Timer time) {
      _currentPage += 1;
      if (_currentPage == bannerList.length) {
        _currentPage = 0;
      }
      pageController.animateToPage(_currentPage,
          duration: Duration(seconds: 1), curve: ElasticOutCurve());
    });
  }

  ///手动改变的时候需要做调整
  _listenPageChange(int dex) {
    _currentPage = dex;
  }

  ///banner UI
  Widget _getBannerUi(BannerEntity entity) {
    return GestureDetector(
      child: AspectRatio(
        aspectRatio: 2.0 / 1.0,
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: NetworkImage(entity.imageUrl),
              fit: BoxFit.fill,
            ),
          ),
          child: Padding(
            padding: EdgeInsets.only(left: 5.0, bottom: 5.0),
            child: Text(
              entity.title,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                fontSize: 16.0,
                color: Colors.blueAccent,
              ),
            ),
          ),
          alignment: AlignmentDirectional.bottomStart,
        ),
      ),
      onTap: () {
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (BuildContext context) {
          return PageWeb(
            title: entity.title,
            webUrl: entity.url,
          );
        }));
      },
    );
  }
}

// "desc":"通过聊天机器人打造智能化工作流",
//"id":17,
//"imagePath":"http://www.wanandroid.com/blogimgs/dd6017a9-f79b-45e3-ae1b-5719a17b0cac.png",
//"isVisible":1,
//"order":0,
//"title":"通过聊天机器人打造智能化工作流",
//"type":0,
//"url":"https://bearychat.com?utm_source=wanandroid&utm_medium=banner&utm_campaign=pc"
///轮播图 实体类
class BannerEntity {
  String imageUrl;
  String title;
  String des;
  String url;

  BannerEntity({this.imageUrl, this.title, this.des, this.url});

  factory BannerEntity.fromJson(Map<String, dynamic> map) {
    return BannerEntity(
      imageUrl: map['imagePath'],
      title: map['title'],
      des: map['des'],
      url: map['url'],
    );
  }
}

///富文本 呈现特殊状态
//new RichText(
//text: new TextSpan(
//text: 'Hello ',
//style: DefaultTextStyle.of(context).style,
//children: <TextSpan>[
//new TextSpan(
//text: 'bold',
//style: new TextStyle(fontWeight: FontWeight.bold)),
//new TextSpan(text: ' world!'),
//],
//),
//)
